package com.zx.crowdfunding.filter;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zx.crowdfunding.constant.AccessPassResources;
import com.zx.crowdfunding.constant.CrowdFundingConstant;

/**
 * 自定义的访问过滤器
 * @author 郑雪
 * @date 2022-01-01
 */
@Component
public class CrowdFundingAccessFilter extends ZuulFilter {

	/**
	 * 是否需要过滤
	 */
	@Override
	public boolean shouldFilter() {
		
		// 1.获取RequestContext对象
		RequestContext requestContext = RequestContext.getCurrentContext();
		
		// 2.通过RequestContext对象获取当前请求对象（框架底层是借助ThreadLocal从当前线程上获取事先绑定的Request对象）
		HttpServletRequest request = requestContext.getRequest();
		
		// 3.获取servletPath值
		String servletPath = request.getServletPath();
		
		// 4.根据servletPath判断当前请求是否对应可以直接放行的特定功能
		if(AccessPassResources.PASS_RESOURCES_SET.contains(servletPath)) {
			
			// 返回false，放行
			return false;
		}
		
		// 5.判断当前请求是否为静态资源
		if(AccessPassResources.judgeCurrentServletPathWetherStaticResource(servletPath)) {
			
			// 返回false，放行
			return false;
		}
		
		// 返回true，执行run()方法
		return true;
	}

	/**
	 * 过滤方法，验证登录
	 */
	@Override
	public Object run() throws ZuulException {
		
		// 1.获取当前请求对象
		RequestContext requestContext = RequestContext.getCurrentContext();
		HttpServletRequest request = requestContext.getRequest();
		
		// 2.获取当前Session对象
		HttpSession session = request.getSession();
		
		// 3.尝试从Session对象中获取已登录的用户
		Object memberLoginVO = session.getAttribute(CrowdFundingConstant.ATTR_NAME_LOGIN_MEMBER);
		
		// 4.判断memberLoginVO是否为空
		if(memberLoginVO == null) {
			
			// 5.从RequestContext对象中获取Response对象
			HttpServletResponse response = requestContext.getResponse();
			
			// 6.将提示消息存入Session域
			session.setAttribute(CrowdFundingConstant.ATTR_NAME_MESSAGE, CrowdFundingConstant.MESSAGE_ACCESS_FORBIDDEN);
			
			// 7.重定向auth-consumer工程中的登录页面
			try {
				response.sendRedirect("/auth/member/to/login/page");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return null;
	}

	/**
	 * 过滤类型
	 */
	@Override
	public String filterType() {
		
		// 这里返回“pre”意思是在目标微服务前执行过滤
		return "pre";
	}

	/**
	 * 过滤排序
	 */
	@Override
	public int filterOrder() {
		return 0;
	}

}
